// pages/home/home.ts
const setting = require("../../http/env");
const httpApi = require("../../http/request"); //后续可以改为你自己的域名接口地址
var app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    //默认域名
    baseUrl: setting.baseUrl,
    //授权
    wxCode: "",
    nickName: "",
    avatarUrl: "",
    sex: "",
    session_key: "",
    openid: "",
    sq_phone: false,
    needAuth: false,
    canIUseGetUserProfile: false,
    //版本号
    wx_version: "",
    //用户
    userInfo: {},
    close_status: false,
    close_tt: "",

    //唯一标识
    unitid: "",
    unitid_copy: "",
    index_title: "",

    //积分记录
    showRecord: false,
    //书果币记录
    showCoinRecord: false,
    //奖品弹窗
    showPrize: false,
    //排行榜
    showRank: false,
    rankTab: 0,
    //头像昵称
    showNickImg: false,
    // 次数用尽提示
    showRemind: false,
    // 盲盒 
    showBlindBox: false,

    //好友匹配的
    quest_rule_id: 0,
    home_user_id: 0,
    musicVideo: null,

    prizeList: [], // 奖品列表

    inviterId: null, // 邀请人id
    studentId: undefined, // 学生id
    tenantId: undefined, // 租户id
    showXingTu: false,
  },

  // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
  // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
  getUserProfile() {
    var that = this;
    wx.getUserProfile({
      desc: "用于完善会员资料", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        that.wxGetInfo(res.userInfo);
      },
    });
  },
  // open-type="getUserInfo"
  bindGetUserInfo(e) {
    this.wxGetInfo(e.detail.userInfo);
  },

  // wx获取用户信息
  wxGetInfo(wxUserInfo) {
    var that = this;
    console.log("wxUserInfo", wxUserInfo);

    if (!that.data.openid) {
      var params = {
        code: that.data.wxCode,
        nickName: '',
        avatarUrl: '',
        sex: '',
        unitid: that.data.unitid,
        unitid_copy: that.data.unitid_copy,
        inviterId: that.data.inviterId || undefined,
        studentId: that.data.studentId,
        tenantId: that.data.tenantId,
      };
      httpApi.Post("/index/hasAccredit", params).then((resInfo) => {
        console.log("resInfo", resInfo);
        if (resInfo.status == -1) return
        that.setData({
          // nickName: wxUserInfo.nickName,
          // avatarUrl: that.data.defaultAvatarUrl,
          // sex: wxUserInfo.gender,
          session_key: resInfo.data.session_key,
          openid: resInfo.data.openid,
          sq_phone: resInfo.data.flag == 1 ? false : true,
        });
        if (resInfo.data.flag == 1) {
          that.getUserInfoByApi(resInfo.data.id);
          that.getPrizeList(resInfo.data.id); // 已经授权过，有用户信息，打开奖品弹窗
        }
      });
    } else {
      that.setData({
        sq_phone: true,
      });
    }
  },
  // 授权手机号
  getPhoneNumber(e) {
    var that = this;
    console.log(e); // 动态令牌
    const params = {
      encrypData: e.detail.encryptedData,
      ivData: e.detail.iv,
      code: that.data.wxCode,
      nickName: that.data.nickName,
      avatarUrl: that.data.avatarUrl,
      sex: that.data.gender,
      session_key: that.data.session_key,
      openid: that.data.openid,
      unitid: that.data.unitid,
      unitid_copy: that.data.unitid_copy,
      inviterId: that.data.inviterId || undefined,
      studentId: that.data.studentId,
      tenantId: that.data.tenantId,
    }
    httpApi
      .Post("/index/accreditNickPhone", params)
      .then((res) => {
        var user = wx.getStorageSync("userInfo") || {};
        wx.setStorageSync("userInfo", Object.assign({}, user, res.data));

        that.setData({
          userInfo: res.data,
          needAuth: false,
          sq_phone: false,
        });

        if (res.data.is_close == 1 || res.data.is_end == 1) {
          var close_status = false;
          var close_tt = "";
          if (res.data.is_close == 1) {
            close_status = true;
            close_tt = "该门店已关闭，暂时不能游戏！";
          }

          if (res.data.is_end == 1) {
            close_status = true;
            close_tt = "活动已结束，暂时不能游戏！";
          }

          that.setData({
            quest_rule_id: 0,
            home_user_id: 0,
            close_status: close_status,
            close_tt: close_tt,
            nickName: res.data.nickname,
            avatarUrl: res.data.headimg
          });
        }

        // 已经授权过，有用户信息，打开奖品弹窗
        that.getPrizeList();
        //跳转好友对战
        if (res.data.grade_id != 0) {
          that.jumpPk();
        }
      });
  },

  //取消手机号
  quxiao_phone(e) {
    var that = this;
    that.setData({
      sq_phone: false,
    });
  },

  //跳转好友对战
  jumpPk(e) {
    var that = this;
    var quest_rule_id = that.data.quest_rule_id;
    var home_user_id = that.data.home_user_id;
    if (quest_rule_id && home_user_id) {
      that.setData({
        quest_rule_id: 0,
        home_user_id: 0,
      });
      wx.navigateTo({
        url:
          "../friendVs/friendVs?quest_rule_id=" +
          quest_rule_id +
          "&home_user_id=" +
          home_user_id,
      });
    }
  },

  //是否关闭了门店
  shopClose(e) {
    var that = this;
    var type = e.currentTarget?.dataset?.type;
    var user = that.data.userInfo;
    var params = {
      unitid: user.unitid,
    };
    httpApi.Post("/index/shopClose", params).then((res) => {
      // console.log("data", res);

      var close_status = false;
      var close_tt = "";
      if (res.is_close == 1) {
        close_status = true;
        close_tt = "该门店已关闭，暂时不能游戏！";
      }

      if (res.is_end == 1) {
        close_status = true;
        close_tt = "活动已结束，暂时不能游戏！";
      }

      that.setData({
        close_status: close_status,
        close_tt: close_tt,
      });

      if (res.is_close == 0 && res.is_end == 0) {
        if (type == "free") {
          this.getRobotCount()
        }
        if (type == "friend") {
          wx.navigateTo({
            url: "/pages/friendVs/friendVs",
          });
        }
      }
    });
  },

  toFirendVs() {
    wx.navigateTo({
      url: "/pages/friendVs/friendVs",
    });
    this.setData({
      showRemind: false
    })
  },

  // 查询今天能和机器人对战几次
  getRobotCount() {
    var user = wx.getStorageSync("userInfo") || {};
    if (user.limit_count_flag == 0) {
      wx.navigateTo({
        url: "/pages/pk-loading/pk-loading",
      });
      return;
    }
    httpApi.Post("/index/lastRobotCount", {user_id: wx.getStorageSync("userInfo").id}).then((res) => {
      if (res.limit <= res.count) {
        this.setData({
          showRemind: true,
        });
      } else {
        wx.navigateTo({
          url: "/pages/pk-loading/pk-loading",
        });
      }
    })
  },

  //关闭弹窗
  closeClose(e) {
    var that = this;
    that.setData({
      close_status: false,
    });
  },

  // 打开书果币记录
  openCoinRecord() {
    this.setData({
      showCoinRecord: true,
    });
  },
  closeCoinRecord() {
    this.setData({
      showCoinRecord: false,
    });
  },
  // 打开奖品
  openPrize() {
    // 跳转页面，后台配置
    wx.navigateTo({
      url: "/pages/prize-list/prize-list",
    });
  },
  closePrize() {
    this.setData({
      showPrize: false,
    });
  },
  // 打开排行榜
  openRank(e) {
    console.log("openRank", e.currentTarget.dataset.tab),
      this.setData({
        showRank: true,
        rankTab: e.currentTarget.dataset.tab,
      });
  },
  closeRank() {
    this.setData({
      showRank: false,
    });
  },
  closeGrade(e) {
    this.setData({
      ["userInfo.grade_id"]: e.detail,
    });
    //跳转好友对战
    this.jumpPk();
  },
  //积分记录
  openRecord() {
    this.setData({
      showRecord: true,
    });
  },
  closeRecord() {
    this.setData({
      showRecord: false,
    });
  },

  //跳转规则
  jump_rule(e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: "../rule/rule?type=" + type,
    });
  },

  //头像昵称
  openNick(e) {
    var that = this;
    console.log("that.data.userInfo.nickname", e);
    this.setData({
      showNickImg: true,
    });
    // if (that.data.userInfo.nickname == "微信用户" || e.detail?.jumpIf) {
    //   this.setData({
    //     showNickImg: true,
    //   });
    // }
  },
  closeNick(e) {
    this.setData({
      showNickImg: false,
    });
    this.getUserInfoByApi();
  },

  closeRemind() {
    this.setData({
      showRemind: false,
    });
  },

  // 开始比赛
  startGame() {
    wx.navigateTo({
      url: "/pages/pk-loading/pk-loading",
    });
  },
  // 跳转到好友对战
  toVsPage() {
    wx.navigateTo({
      url: "/pages/friendVs/friendVs",
    });
  },
  // 跳转获奖中心
  toPrizePage() {
    console.log("iris");
    wx.navigateTo({
      url: "/pages/prize-list/prize-list",
    });
  },
  // 跳转到知识图谱
  toKonwledgePage() {
    wx.navigateTo({
      url: "/pages/knowledge-new/knowledge-new",
    });
  },
  // 跳转盲盒详情
  toBlindBox() {
    this.setData({
      showBlindBox: false,
    });
    wx.navigateTo({
      url: "/pages/blind-box-detail/blind-box-detail",
    });
  },

  // 获取用户信息
  getUserInfoByApi(userId) {
    var that = this;
    var user = that.data.userInfo;
    httpApi.Post("/index/getUser", { user_id: userId || user.id }).then((res) => {
      if (res.status == -1) {
        wx.setStorageSync("userInfo", "");
        that.setData({
          userInfo: {},
          needAuth: true,
        });
      } else {
        var user = wx.getStorageSync("userInfo") || {};
        wx.setStorageSync("userInfo", Object.assign({}, user, res.data));
        that.setData({
          userInfo: res.data,
          needAuth: false,
        });
        if (user.mystery_box_flag == 1) this.getFirstOne();
      }
    });
  },

  // 是否第一次对决
  getFirstOne() {
    // 不存在邀请且第一次打开得到盲盒
    httpApi.Post("/index/firstOne", { user_id: this.data.userInfo.id }).then((res) => {
      if (res.status) return
        
      if (res.data.flag == 0) {
        this.setData({
          showBlindBox: true,
        });
      }
    });
  },

  // 获取奖品列表
  getPrizeList(userId) {
    httpApi
      .Post("/index/getUserWin", { user_id: userId || wx.getStorageSync("userInfo").id })
      .then((res) => {
        console.log(res);
        this.setData({
          prizeList: res.data,
          showPrize: res.data.length ? true : false,
        });
      });
  },

  // 获取标题名称
  getIndexTt() {
    httpApi.Post("/index/getIndexTt", {}, "").then((res) => {
      console.log(res);
      this.setData({
        index_title: res.data.index_title,
      });
    });
  },

   // 获取用户过期时间
   getFlagexpired() {
    httpApi.Get("/index/flagexpired", {}, "").then((res) => {
      // 存入门店标识
      wx.setStorageSync("userInfo", {
        unitid: this.data.unitid,
        unitid_copy: this.data.unitid_copy,
        expired: res.data.expired,
        limit_count_flag: res.data.limit_count_flag, // 对战次数限制 0-不限制 1-限制
        mystery_box_flag: res.data.mystery_box_flag, // 盲盒功能 0-关闭 1-开启
        round_flag: res.data.round_flag, // 再来一局 0-不显示 1-显示
        show_book_flag: res.data.show_book_flag, // 显示书籍 0-不显示 1-显示
        star_map_flag: res.data.star_map_flag, // 星图功能 0-显示 1-不显示
      });

      // 星图功能 0-关闭 1-开启
      this.setData({
        showXingTu: res.data.star_map_flag == 0,
      });
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    //房主user_id
    var home_user_id = options.home_user_id ? options.home_user_id : 0;
    //答题匹配id
    var quest_rule_id = options.quest_rule_id ? options.quest_rule_id : 0;
    //唯一标识
    var unitid = options.unitid ? options.unitid : "";
    //唯一标识copy
    var unitid_copy = options.unitid_copy ? options.unitid_copy : "";
    // 学生id
    var studentId = options.studentId ? options.studentId : undefined;
    // 租户id
    var tenantId = options.tenantId ? options.tenantId : undefined;
    if(unitid == 'undefined'){
      unitid='';
    }
    if(unitid_copy == 'undefined'){
      unitid_copy='';
    }
    if (studentId) {
      wx.setStorageSync("userInfo", "");
    }

    // 如果存了用户信息，就不需要再次授权
    var user = wx.getStorageSync("userInfo") || {};
    if (!user || !user.id) {
      var needAuth = true;
      if (!unitid) unitid = user.unitid || ''
      if (!unitid_copy) unitid_copy = user.unitid_copy || ''
    } else if (new Date().getTime() > new Date(user.expired).getTime()) {
      // 如果过期了，重新授权
      wx.setStorageSync("userInfo", "");
      var needAuth = true;
    } else {
      var needAuth = false;
    }
    that.getFlagexpired();

    console.log('携带参数unitid:', options.unitid, 'unitid_copy:', options.unitid_copy, '最终参数unitid:', unitid, 'unitid_copy:', unitid_copy, '租户id:', tenantId, '学生id:', studentId);
    that.setData({
      userInfo: user,
      needAuth: needAuth,
      home_user_id: home_user_id,
      quest_rule_id: quest_rule_id,
      unitid: unitid,
      unitid_copy: unitid_copy,
      inviterId: options.inviterId || null,
      studentId: studentId,
      tenantId: tenantId,
    });

    wx.getSystemInfo({
      success: function (res) {
        let wx_version = res.SDKVersion;
        wx_version = wx_version.replace(/\./g, "");
        console.log("当前版本号: " + wx_version);
        that.setData({
          wx_version: wx_version,
        });
      },
    });

    // 授权
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true,
      });
    }
    wx.login({
      success: function (resLogin) {
        console.log("login", resLogin);
        that.setData({
          wxCode: resLogin.code,
        });
        if (studentId) {
          that.wxGetInfo({});
        }
      },
    });

    //获取标题名称
    that.getIndexTt();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},
  // 播放音频
  playVideo() {
    this.data.musicVideo = wx.createInnerAudioContext({
      useWebAudioImplement: true,
    });
    this.data.musicVideo.loop = true; // 循环
    this.data.musicVideo.src =
      "https://game.shuguos.com/upload/video/video-home.mp3";
    this.data.musicVideo.play(); // 播放
  },
  // 停止播放音频并释放
  stopVideo() {
    this.data.musicVideo.stop(); // 停止音频资源
    this.data.musicVideo.destroy(); // 释放音频资源
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // this.playVideo();
    var user = wx.getStorageSync("userInfo");

    if (user && user.id) {
      this.getUserInfoByApi();
      this.getPrizeList(); // 已经授权过，有用户信息，打开奖品弹窗
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    // this.stopVideo();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // this.stopVideo();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
    var user = wx.getStorageSync("userInfo");
    var path =
      "/pages/home/home?unitid=" +
      user.unitid +
      "&unitid_copy=" +
      user.unitid_copy + 
      "&inviterId=" + 
      wx.getStorageSync("userInfo").id;
    return {
      title: app.globalData.shareInfo[e.from].title,
      imageUrl: app.globalData.shareInfo[e.from].imageUrl,
      path: path,
      success: function (res) {
        // 转发成功
        console.log(11212);
      },
      fail: function (res) {
        // 转发失败
      },
    };
  },
});
